function HPZ_Interface

% This file collects the information on the required estimation and reports
% the results to the user.
global numeric_flag
global output_flag_vec
global fid_MME_final_report
global fid_NLLS_final_report
%% "True" value of this boolean flag restricts beta to be equal to zero
global beta_zero_flag
%% "True" value of this boolean flag restricts rho to be equal to zero
global rho_zero_flag
% The max number of convergance points MME
global MME_min_counter;
% The max number of convergance points NLLS
global NLLS_min_counter;
%% TO BE DONE
% Time (minutes) that user want to spend on running the code on his machine
global MME_max_time_estimation
global NLLS_max_time_estimation
%% TO BE ADDED
% % % now we only use max 100 iterations as our upper bound
% % global max_starting_points

% Select a data set. This code accomodates choi et al. (2007) only. 
% Additional data sets can be added easily as long as the data is arranged 
% in an equivalent manner. 

data_set=0;

while ~(data_set==1)

    data_set = listdlg('PromptString','Data Set Selection',...
                'SelectionMode','single', 'ListString',{'Choi et. al (2007)'},...
                'Name','Data Set','ListSize',[250 100],'uh',30,'fus',8,'ffs',8);         
end


% % % num_goods = 0;
% % % while ~((num_goods==2)||(num_goods==3))
% % % %     num_goods = number_of_goods();
% % %        goods = questdlg('Specify the number of Goods?', 'Number of Goods Selection', ...
% % %         'Two','Three','Two');
% % %         switch goods
% % %             case 'Two'
% % %                 num_goods = 2;
% % %             case 'Three'
% % %                 num_goods = 3;
% % %         end
% % % end

treatment=0;
   
while ~((treatment==1)||(treatment==2)||(treatment==3)||(treatment==4))

    treatment = listdlg('PromptString','Treatment Selection',...
                'SelectionMode','single', 'ListString',{'Symmetric',...
                'Asymmetric (probability of third to state 1)',...
                'Asymmetric (probability of two-thirds to state 1)'},...
                'Name','Treatment','ListSize',[400 100],'uh',30,'fus',8,'ffs',8);
            
end

action=0;
   
while ~((action==1)||(action==2)||(action==3))

     action = listdlg('PromptString','Action Selection',...
                'SelectionMode','single', 'ListString',{'Consistency Tests and Inconsistency Indices',...
                'Nonlinear Least Squares',...
                'Money Metric Method'},...
                'Name','Data Set','ListSize',[500 50],'uh',30,'fus',8,'ffs',8);
end

% Extracting the data of Choi et. al (2007)

if (data_set==1)
    
    data_matrix = HPZ_CFGK_2007_Format_Data (treatment);

end    

% At this point we assume that data_matrix has a specific structure:
% The matrix has six columns (We assume that the endowment is fixed at 1):
% The first column is the subject ID.
% The second column is the observation number - 50 observations per subject
% The third column is the quantity of good 1 chosen by the subject.
% The fourth column is the quantity of good 2 chosen by the subject.
% The fifth column is the price of good 1. 
% The sixth column is the price of good 2. 

% list of subjects' numbers in the required treatment

subjects = unique(data_matrix(:,1));

subjects_str = num2str(subjects);

obs_num = length(unique(data_matrix(:,2)));

legal_assignment=0;
   
while ~(legal_assignment==1)
    
    legal_assignment=1;
    
    subjects_index = listdlg('PromptString','Subjects Selection (the same action applies to all)',...
                'SelectionMode','multiple', 'ListString',subjects_str,...
                'Name','Subjects','ListSize',[400 600],'uh',30,'fus',8,'ffs',8);
    
    chosen_subjects_num = length(subjects_index);
            
    for i=1:chosen_subjects_num

        if isempty(find(subjects==data_matrix(subjects_index(i)*obs_num,1), 1))
            
           legal_assignment=0;
            
        end
            
    end
end

% if estimation was chosen we need some more information
if ((action==2)||(action==3))
    
% % % %     %% Preference Classification
% % % %     pref_class = 0;
% % % %     if pref_class == 0
% % % %         pref_class = HPZ_Interface_Preference_classification();
% % % %         % set the preference class
% % % %         % pref_class = 1 % Risk Behavior
% % % %     end
    
    pref_class = 1; % Risk Behavior
    if pref_class == 1
        % the following is specific information needed for the estimation 
        % of Choi et al. (2007) data set.
        [function_flag, numeric_flag, beta_flag, beta_zero_flag, rho_zero_flag, ...
          asymmetric_flag, zeros_flag] = HPZ_Interface_Functional_form_settings(action, treatment);
    end
    
	% if estimation was chosen we need some more information
	[MME_min_counter, MME_max_time_estimation, aggregation_flag, ...
          NLLS_min_counter, NLLS_max_time_estimation, metric_flag, parallel_flag] = HPZ_Interface_Optimization_settings(action);
    
    [output_flag_vec] = HPZ_output_file_format;
    
    
    %% Setting the result files   
    if action == 2 % NLLS
        %% organize the output file NLLS
        % create a the output file
        if function_flag == 1 %% CRRA
            param_2 = 'Rho';
        else %% CARA
            param_2 = 'A';
        end
        fid_NLLS_final_report = fopen(strcat('NonlinearLeastSquares-Results', '.csv'), 'w');
        %% finalize the output file for distinct results
        fprintf(fid_NLLS_final_report, '%s,%s,%s,%s,%s,%s,%s,%s,%s\n', ...
                                      'Beta',param_2, ...
                                      'Criterion_NLLS_CFGK_Metric', 'Criterion_NLLS_Euclidean_Metric', ...
                                      'Criterion_MME_Max_Waste', 'Criterion_MME_Mean_Waste', 'Criterion_MME_SumOfSquares_Wastes',...
                                      'Time(sec)','Subject');
    end
    
    if action == 3 % MME
        %% organize the output file MME
        % create a the output file
        if function_flag == 1 %% CRRA
            param_2 = 'Rho';
        else %% CARA
            param_2 = 'A';
        end
        fid_MME_final_report = fopen(strcat('MoneyMetricMethod-Results', '.csv'), 'w');
        %% finalize the output file for distinct results
        fprintf(fid_MME_final_report, '%s,%s,%s,%s,%s,%s,%s,%s,%s\n', ...
                                      'Beta',param_2, ...
                                      'Criterion_NLLS_CFGK_Metric', 'Criterion_NLLS_Euclidean_Metric', ...
                                      'Criterion_MME_Max_Waste', 'Criterion_MME_Mean_Waste', 'Criterion_MME_SumOfSquares_Wastes',...
                                      'Time(sec)','Subject');
    end
    
      %% Set matlabpool (Parallel Computing)
      if parallel_flag
          % if parallel flag is on
          
          % close all other session
          matlabpool close force local;
          
          % use all resources
          matlabpool;
      end
end


for i=1:chosen_subjects_num
    
  data = data_matrix(obs_num*(subjects_index(i)-1)+1:obs_num*subjects_index(i),:);
  
  if action==1
  
    Choices(:,1:2)=data(1:obs_num,3:4);
    
    Choices(:,3:4)=data(1:obs_num,5:6);

    % the function can return the disaggregated matrices of violations, we
    % dont report it.
    [~,~,~,~,~,~,~,~,~,~,VIO_PAIRS,VIOLATIONS,AFRIAT,VARIAN,HM] = HPZ_Subject_Consistency (Choices);
  
    str_WARP=['There are ',num2str(VIOLATIONS(1)),' WARP violations (',num2str(VIO_PAIRS(1)),' pairs).'];
    str_WGARP=['There are ',num2str(VIOLATIONS(2)),' WGARP violations (',num2str(VIO_PAIRS(2)),' pairs).'];
    str_GARP=['There are ',num2str(VIOLATIONS(3)),' GARP violations (',num2str(VIO_PAIRS(3)),' pairs).'];
    str_SARP=['There are ',num2str(VIOLATIONS(4)),' SARP violations (',num2str(VIO_PAIRS(4)),' pairs).'];
    str_afriat=['The Afriat index is ',num2str(AFRIAT)];
    str_varian_min=['The Minimal Varian index is ',num2str(VARIAN(1))];
    str_varian_average=['The Average Varian index is ',num2str(VARIAN(2))];
    str_varian_ssq=['The SSQ of Varian index is ',num2str(VARIAN(3))];
    str_hm=['The Houtman-Maks index is ',num2str(HM)];
    
    str(1) = cellstr(str_WARP);
    str(2) = cellstr(str_WGARP);  
    str(3) = cellstr(str_GARP);  
    str(4) = cellstr(str_SARP);      
    str(5) = cellstr(str_afriat);  
    str(6) = cellstr(str_varian_min);  
    str(7) = cellstr(str_varian_average);  
    str(8) = cellstr(str_varian_ssq);  
    str(9) = cellstr(str_hm);      
    
    str_title=['Subject ',num2str(data(1,1))];
    
    msgbox(str,str_title);
    
  end
  
  if action==2
    % Perform the estimation NLLS
    HPZ_NLLS (data,obs_num,treatment,function_flag,beta_flag,zeros_flag,metric_flag,asymmetric_flag);
       
  end
  
  if action==3
    % Perform the estimation MME
    HPZ_MME_Estimation (data,obs_num,treatment,function_flag,beta_flag,zeros_flag,aggregation_flag);  
    
  end
  
end

    if action==2 % NLLS
        % close the result file
        fclose(fid_NLLS_final_report);
        % Address the result file
        h_ms_NLLS = msgbox(strcat('The result file is saved as " StatisticalMethod-Results.CSV " under the following path:  ', pwd), 'Output File Path','help');
    end
    
    if action==3 % MME
        % close the result file
        fclose(fid_MME_final_report);
        % Address the result file
        h_ms_MME = msgbox(strcat('The result file is saved as " MoneyMetricMethod-Results.CSV " under the following path:  ', pwd), 'Output File Path','help');
    end

end